package com.shark.demo;

import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName CASDemo
 * @Description TODO
 * @Author 东北彭于晏
 * @Date 2024/9/29  15:55
 * @Version 1.0
 **/

public class CASDemo {
    private volatile int number = 0;//保证可见性
    AtomicInteger atomicInteger = new AtomicInteger(0);

    public int getNumber() {
        return number;
    }

    public synchronized void setNumber() {
        number++;
    }

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
        atomicInteger.getAndIncrement();
    }

    public static void main(String[] args) throws InterruptedException {
        CASDemo casDemo = new CASDemo();
        CountDownLatch countDownLatch = new CountDownLatch(100);

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    casDemo.setNumber();
                    casDemo.setAtomicInteger();
                }
                countDownLatch.countDown();
            }, String.valueOf(i)).start();

        }
        countDownLatch.await();

        System.out.println(casDemo.getNumber());
        System.out.println(casDemo.getAtomicInteger());
    }
}

